<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
require_once("../Scripts/authenticate.php"); //Only users who are logged in can access this page
require_once("../Scripts/DatabaseConnect.php");
require_once("../Scripts/UpdateStocks.php");//Checks if we need to update the database with new market data.

//Check if we need local server or remote server
$con=Remoteconnect();
if($con==null){
	$con=Localconnect();	
}
//Display the last update date and current date and time.
$lastUpdate="";
$result = mysqli_query($con,"SELECT * FROM  `time`");

while($row = mysqli_fetch_array($result)) {
	$lastUpdate=$row['LastUpdate'];

  
}

$date = date('m-d-Y h:i:s a', time());//gets current date and time of server.
echo"Date: $date, Last Update: $lastUpdate";
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN" dir="ltr">
<head profile="http://gmpg.org/xfn/11">
<title>J&J Free Stock backtesting</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="imagetoolbar" content="no" />
<link rel="stylesheet" href="businesstoday/styles/layout.css" type="text/css" />
</head>
<body id="top">
<div class="wrapper col1">
  <div id="header">
    <img src="../Images/the-top-5-high-volume-trading-stocks-of-the-week_1118_437849_0_14042581_500.jpg" alt="" width="240" height="162" />
    <div id="logo">
      <h1>J&amp;J Free Stock Backtesting    </h1>
    </div>
    <div id="newsletter">
    <div id="login" style="display:block; min-height:50px; min-width:600px;">
      <p><a href="#">Lost your password?</a> <a href="register.php">Register</a>

      </p>
      
      <form action="../Scripts/authenticate.php" method="post" >
      
        <fieldset>
          <legend>NewsLetter</legend>
          <table>
            <tr>
              <td>Name:</td>
              <td><input type="email" name="email" required="required" id="email" /></td>
              <td>Password:</td>
              <td><input type="password" name="password" required="required" id="password" /></td>
              <td><input type="submit" name="news_go" id="news_go" value="Login" /></td>
            </tr>
          </table>
        </fieldset>
      </form>


      </div>
      
      <?php
	  //Wrong password message
      if (isset($_SESSION['msg'])) {
	echo "<p style='color:red'>".$_SESSION['msg']."</p>"; 
	//remove the message since it has been displayed.
	unset($_SESSION['msg']);
	}
	?>
    
   	<?php
	//logout button
    if (isset($_SESSION['msgG'])) {
		echo"<form>";
		echo "<p style='color:green'>".$_SESSION['msgG']."</p>"; 
		echo '<input type="button" name="logout" id="logout" value="Logout" onClick="location.href=\'../Scripts/Logout.php\'"/>'; 
		echo"</form>";
	}
	
?> 
  

    </div>
    <br class="clear" />
  </div>
</div>

<div class="wrapper col2">
  <div id="topbar">
    <div id="topnav">
      <ul>
        <li class="active">
         
              <li><a href="index.php">Home Page</a></li>
              <li id="portfolio" style="display:none"><a href="portfolio.php">Stock Portfolio</a></li>
              <li id="stockMonitoring" style="display:none"><a href="stockMonitoring.php">Stock Monitoring</a></li>
              <li><a href="stockbacktest.php">Stock Backtest</a></li>
              <li><a href="charts.php">Stock Charts</a>
               <ul>
            <li><a href="chartDifShares.php">Stock Prices Comparision Chart</a></li>
            <li><a href="chartIndicators.php">Stock Technical Analysis Chart</a></li>
         
          </ul>
        </li>

        
  </li>      
        
        
      </ul>
    </div>
 <script type="text/javascript">
 //Hides/Shows navigation bar links based on logged in status
	  var check = <?php echo json_encode(isset($_SESSION['email'])); ?>;
	  
	  if(check==true){
		  document.getElementById("login").style.display="none";
		  document.getElementById("portfolio").style.display="block";
		  document.getElementById("stockMonitoring").style.display="block";

	  }else{
		  document.getElementById("login").style.display="block";
		  document.getElementById("stockMonitoring").style.display="none";
		  document.getElementById("portfolio").style.display="none";
		  
	  }
	 
 </script>
 
       
    <br class="clear" />
  </div>
</div>
<div class="wrapper col3">  <div id="intro">
    <div class="fl_right"></div>
          <p><a href="PortfolioStats.php">Portfolio Stats</a>&nbsp;&nbsp;&nbsp;<a href="PortfolioTrans.php">Transaction Data</a>&nbsp;&nbsp;&nbsp;<a href="EditData.php">Edit Transaction Data</a></p>
<br class="clear" />
  </div>
</div>
<div class="wrapper col4"></div>
<div class="wrapper col5">
  <div id="container">
    <div id="content"style=" max-height:900px; overflow:auto">
      <h2>Portfolio Stats</h2>

       <?php
                    $con = Remoteconnect();
                    if ($con == null) {
                        $con = Localconnect();
                    }
					//porfolio result data initialised
                    $PortfolioChange = 0;
                    $PortfolioCostBasis = 0;
                    $PortfolioMktValue = 0;
                    $PortfolioGain = 0;
                    $PortfolioGainPercent = 0;
                    $PortfolioDaysGain = 0;


                    //Symbol arrays 
                    $Symbols = array();
                    $DuplicateSymbols = array();
                    $UniqueSymbols = array();

                    $result = mysqli_query($con, "SELECT * FROM `userportfolio` WHERE Email ='" . $_SESSION['email'] . "' AND `Symbol` != ''");
                    while ($row = mysqli_fetch_array($result)) {
                        array_push($Symbols, $row['Symbol']);
                    }
                    //Find duplicate symbols:
                    $SymbolsCount = array_count_values($Symbols);

                    foreach ($SymbolsCount as $key => $val) {
                        if ($val == 1) {
                            array_push($UniqueSymbols, $key);
                        } else {
                            array_push($DuplicateSymbols, $key);
                        }
                    }

                    foreach ($DuplicateSymbols as $Symbol) {

                        //Calcualte the total shares and cost basis for each of the users transaction with the same symbol
                        $result = mysqli_query($con, "SELECT * FROM `userportfolio` WHERE Email ='" . $_SESSION['email'] . "' AND `Symbol` ='$Symbol' ORDER BY `Date`");
                        $Count = 0;
                        $CostBasis = 0;
                        $Shares = 0;
                        while ($row = mysqli_fetch_array($result)) {
                            //if the type of the transaction is 'buy' we want to increase the number of shares and therefore increase the cost basis etc.etc
                            if ($row['Type'] == "buy") {
                                $Shares = $Shares + $row['Shares'];
                                $CostBasis = $CostBasis + $row['CashValue'];
								//Get latest closing price and latest previous closing price
								
								//initiating  cURL
								$curl=curl_init();
								//CSV URL obtains current market data from yahoo.
								curl_setopt ($curl,CURLOPT_URL,"http://download.finance.yahoo.com/d/quotes.csv?s=".$Symbol."&f=sl1d1t1c1ohgv&e=.csv");
								
								
								curl_setopt ($curl,CURLOPT_HEADER,0);
								ob_start();
								curl_exec ($curl);
								curl_close ($curl);
								$data=ob_get_clean(); 
								//splitting the data into an array 
								$data=explode(",",$data);
								//replacing the " character with nothing
								$data=str_replace('"', '', $data);
								//getting the data out of the array
								$ClosePrice=$data[1];
								$CurrentDate=$data[2];
								$PreviousClosePriceDiference=$data[4];
								
								if($PreviousClosePriceDiference<0){
								
								//replace and negative sign from the data
								$PreviousClosePriceDiference=str_replace('-', '', $PreviousClosePriceDiference);
								
								$PreviousClosePrice=$PreviousClosePriceDiference+$ClosePrice;
								//Change the difference back to being below 0 to avoid running the below if statement
								$PreviousClosePriceDiference=-$PreviousClosePriceDiference;
								
								}
								if($PreviousClosePriceDiference>0){
									$PreviousClosePrice=$ClosePrice-$PreviousClosePriceDiference;
									
								}

								//make calculations
                                $Change = $ClosePrice - $PreviousClosePrice;
                                $MktValue = $Shares * $ClosePrice;
                                $Gain = $MktValue - $CostBasis;
                                $GainPercent = ($MktValue - $CostBasis) / $CostBasis * 100;
                                $DaysGain = ($ClosePrice * $Shares) - ($PreviousClosePrice * $Shares);


                            }
                            //if the type of the transaction is 'sell' then we want to decrease the number of shares in the portfolio that you are selling,
                            //and therefore decrease the cost basis etc.etc
                            if ($row['Type'] == "sell") {
                                $sharesSold = $row['Shares'];
                                $query = mysqli_query($con, "SELECT * FROM `userportfolio` WHERE Email ='" . $_SESSION['email'] . "' AND `Symbol` ='$Symbol' AND `Type`='buy' ORDER BY `Date`");
                                while ($buyrow = mysqli_fetch_array($query)) {
                                    //if shares number greater than the amount brought in the first transaction - the shares sold by the number brought and move onto the next brought

                                    //check if the number of shares is more or less than the number of shares in the current row
                                    	
                                        if ($sharesSold <= $buyrow['Shares']) {
											$commissionSold = ($buyrow['Commission']);
                                            $commissionSold = $commissionSold * ($sharesSold / $buyrow['Shares']);
                                            $Shares = $Shares - $sharesSold;											
                                            $CostBasis = $CostBasis - ($sharesSold * $buyrow['Price'] + $commissionSold);
                                            $sharesSold = 0;
                                        } 
										
										if ($sharesSold > $buyrow['Shares']) {											
											$sharesSolds=$buyrow['Shares'];
											$Shares = $Shares - $sharesSolds;
											$commissionSold = ($buyrow['Commission']);
                                            $commissionSold = $commissionSold * ($sharesSolds / $buyrow['Shares']);									
											$CostBasis = $CostBasis - ($sharesSolds * $buyrow['Price'] + $commissionSold);
											$sharesSold=$sharesSold-$sharesSolds;
											
                                            
                                        }
                                    



									//Get latest closing price and latest previous closing price
									
									//initiating  cURL
									$curl=curl_init();
									//CSV URL obtains all the historical data from yahoo.
									curl_setopt ($curl,CURLOPT_URL,"http://download.finance.yahoo.com/d/quotes.csv?s=".$Symbol."&f=sl1d1t1c1ohgv&e=.csv");
									
									
									curl_setopt ($curl,CURLOPT_HEADER,0);
									ob_start();
									curl_exec ($curl);
									curl_close ($curl);
									$data=ob_get_clean(); 
									//splitting the data into an array 
									$data=explode(",",$data);
									//replacing the " character with nothing
									$data=str_replace('"', '', $data);
									//getting the data out of the array
									$ClosePrice=$data[1];
									$CurrentDate=$data[2];
									$PreviousClosePriceDiference=$data[4];
									
									if($PreviousClosePriceDiference<0){
									
									//replace and negative sign from the data
									$PreviousClosePriceDiference=str_replace('-', '', $PreviousClosePriceDiference);
									
									$PreviousClosePrice=$PreviousClosePriceDiference+$ClosePrice;
									//Change the difference back to being below 0 to avoid running the below if statement
									$PreviousClosePriceDiference=-$PreviousClosePriceDiference;
									
									}
									if($PreviousClosePriceDiference>0){
										$PreviousClosePrice=$ClosePrice-$PreviousClosePriceDiference;
										
									}

									if($Shares!=0){

                                    $MktValue = $Shares * $ClosePrice;
                                    $Gain = $MktValue - $CostBasis;
									$GainPercent = ($MktValue - $CostBasis) / $CostBasis * 100;
                                    $DaysGain = ($ClosePrice * $Shares) - ($PreviousClosePrice * $Shares);



									}else{
										$Shares="0(closed)";
										$MktValue="";
										$Gain="";
										$GainPercent="";
										$DaysGain="";	
									}
									
                                }
                            }
                        }
                        //Display output
                        echo"Symbol: $Symbol<br>";
                        echo"Last Price: $ClosePrice<br>";
                        if ($Change > 0) {
                            echo "<p style='color:green'>Change: " . $Change . "<br></p>";
                        } else {
                            echo "<p style='color:red'>Change: " . $Change . "<br></p>";
                        }

                        echo"Shares: $Shares<br>";
                        echo"Cost Basis: $CostBasis<br>";
                        echo"Mkt Value: $MktValue<br>";
                        if ($Gain > 0) {
                            echo "<p style='color:green'>Gain: " . $Gain . "<br></p>";
                        } 
						if ($Gain < 0) {
                            echo "<p style='color:red'>Gain: " . $Gain . "<br></p>";
                        }
                        if ($GainPercent > 0) {
                            echo "<p style='color:green'>Gain%: " . $GainPercent . "<br></p>";
                        }
						if ($GainPercent < 0){
                            echo "<p style='color:red'>Gain%: " . $GainPercent . "<br></p>";
                        }
                        if ($DaysGain > 0) {
                            echo "<p style='color:green'>Day's gain: " . $DaysGain . "<br></p>";
                        }
						if ($DaysGain < 0){
                            echo "<p style='color:red'>Day's gain: " . $DaysGain . "<br></p>";
                        }

                        echo"____________________<br>";
						$PortfolioChange=$PortfolioChange+$Change;
						$PortfolioCostBasis = $PortfolioCostBasis + $CostBasis;
						
						$PortfolioMktValue = $PortfolioMktValue + $MktValue;
						$PortfolioGain = $PortfolioGain + $Gain;
						$PortfolioGainPercent = ($PortfolioGain/$PortfolioCostBasis) * 100;
						$PortfolioDaysGain = $PortfolioDaysGain + $DaysGain;
                    }

                    foreach ($UniqueSymbols as $Symbol) {
                        $result = mysqli_query($con, "SELECT * FROM `userportfolio` WHERE Email ='" . $_SESSION['email'] . "' AND `Symbol` = '" . $Symbol . "'");


                        while ($row = mysqli_fetch_array($result)) {
                            $Type = $row['Type'];
                            $Date = $row['Date'];
                            $Shares = $row['Shares'];
                            $Price = $row['Price'];
                            $Commission = $row['Commission'];
                            $Notes = $row['Notes'];
							//Get latest closing price and latest previous closing price
							
							//initiating  cURL
							$curl=curl_init();
							//CSV URL obtains all the historical data from yahoo.
							curl_setopt ($curl,CURLOPT_URL,"http://download.finance.yahoo.com/d/quotes.csv?s=".$Symbol."&f=sl1d1t1c1ohgv&e=.csv");
							
							
							curl_setopt ($curl,CURLOPT_HEADER,0);
							ob_start();
							curl_exec ($curl);
							curl_close ($curl);
							$data=ob_get_clean(); 
							//splitting the data into an array 
							$data=explode(",",$data);
							//replacing the " character with nothing
							$data=str_replace('"', '', $data);
							//getting the data out of the array
							$ClosePrice=$data[1];
							$CurrentDate=$data[2];
							$PreviousClosePriceDiference=$data[4];
							
							if($PreviousClosePriceDiference<0){
							
							//replace and negative sign from the data
							$PreviousClosePriceDiference=str_replace('-', '', $PreviousClosePriceDiference);
							
							$PreviousClosePrice=$PreviousClosePriceDiference+$ClosePrice;
							//Change the difference back to being below 0 to avoid running the below if statement
							$PreviousClosePriceDiference=-$PreviousClosePriceDiference;
							
							}
							if($PreviousClosePriceDiference>0){
								$PreviousClosePrice=$ClosePrice-$PreviousClosePriceDiference;
								
							}
							
                            $Change = $ClosePrice - $PreviousClosePrice;
							$CostBasis = $Shares * $Price + $Commission;
                            $MktValue = $Shares * $ClosePrice;
                            $Gain = $MktValue - $CostBasis;
                            $GainPercent = ($MktValue - $CostBasis) / $CostBasis * 100;
                            $DaysGain = ($ClosePrice * $Shares) - ($PreviousClosePrice * $Shares);
							

                            $PortfolioChange = $PortfolioChange + $Change;
							
                            $PortfolioCostBasis = $PortfolioCostBasis + $CostBasis;
							
                            $PortfolioMktValue = $PortfolioMktValue + $MktValue;
                            $PortfolioGain = $PortfolioGain + $Gain;
							
                            $PortfolioGainPercent = ($PortfolioGain/$PortfolioCostBasis) * 100;

                            $PortfolioDaysGain = $PortfolioDaysGain + $DaysGain;

                            echo"Symbol: $Symbol<br>";
                            echo"Last Price: $ClosePrice<br>";
                            if ($Change > 0) {
                                echo "<p style='color:green'>Change: " . $Change . "<br></p>";
                            } else {
                                echo "<p style='color:red'>Change: " . $Change . "<br></p>";
                            }

                            echo"Shares: $Shares<br>";
                            echo"Cost Basis: $CostBasis<br>";
                            echo"Mkt Value: $MktValue<br>";
                            if ($Gain > 0) {
                                echo "<p style='color:green'>Gain: " . $Gain . "<br></p>";
                            } else {
                                echo "<p style='color:red'>Gain: " . $Gain . "<br></p>";
                            }
                            if ($GainPercent > 0) {
                                echo "<p style='color:green'>Gain%: " . $GainPercent . "<br></p>";
                            } else {
                                echo "<p style='color:red'>Gain%: " . $GainPercent . "<br></p>";
                            }
                            if ($DaysGain > 0) {
                                echo "<p style='color:green'>Day's gain: " . $DaysGain . "<br></p>";
                            } else {
                                echo "<p style='color:red'>Day's gain: " . $DaysGain . "<br></p>";
                            }

                            echo"____________________<br>";
                        }
                    }


                    echo"Portfolio Value<br>";
                    if ($PortfolioChange > 0) {
                        echo "<p style='color:green'>Change: " . $PortfolioChange . "<br></p>";
                    } else {
                        echo "<p style='color:red'>Change: " . $PortfolioChange . "<br></p>";
                    }
                    echo"Cost Basis: $PortfolioCostBasis<br>";
                    echo "Mkt Value: $PortfolioMktValue<br>";
                    if ($PortfolioGain > 0) {
                        echo "<p style='color:green'>Gain: " . $PortfolioGain . "<br></p>";
                    } else {
                        echo "<p style='color:red'>Gain: " . $PortfolioGain . "<br></p>";
                    }
                    if ($PortfolioGainPercent > 0) {
                        echo "<p style='color:green'>Gain%: " . $PortfolioGainPercent . "<br></p>";
                    } else {
                        echo "<p style='color:red'>Gain%: " . $PortfolioGainPercent . "<br></p>";
                    }
                    if ($PortfolioDaysGain > 0) {
                        echo "<p style='color:green'>Day's Gain: " . $PortfolioDaysGain . "<br></p>";
                    } else {
                        echo "<p style='color:red'>Day's Gain: " . $PortfolioDaysGain . "<br></p>";
                    }








                    mysqli_close($con);
                    ?>
     
    </div>
    <br class="clear" />
  </div>
</div>
<div class="wrapper col6"></div>
<div class="wrapper col7">
  <div id="copyright">
    <p class="fl_left">Copyright &copy; 2011 - All Rights Reserved - <a href="#">Domain Name</a></p>
    <p class="fl_right">Template by <a href="http://www.os-templates.com/" title="Free Website Templates">OS Templates</a></p>
    <br class="clear" />
  </div>
</div>
</body>
</html>
